import Icon from '@/components/Icon'
import Input from '@/components/Input'
import NavBar from '@/components/NavBar'
import styles from './index.module.scss'
import { useEffect, useRef, useState } from "react"
import { DotLoading, Toast } from 'antd-mobile'
import { RootState } from '@/store'
import { useDispatch, useSelector } from 'react-redux'
import classNames from 'classnames'
import { baseURL } from '@/utils/http'
import { getTokenInfo } from '@/utils/storage'
import { io } from 'socket.io-client'
import { getUserProfile } from '@/store/action/user'
import history from '@/utils/history'
export default function ProfileChat() {

  // ------------从仓库中获取用户信息
  const { userProfile } = useSelector((state: RootState) => state.user)


  // ------------关于消息的发送
  type MsgType = {
    type?: 'robot' | 'user'
    msg: string
    timestamp: number
  }
  const [msg, setMsg] = useState('')
  const [msgState, setMsgState] = useState(false)
  const [list, setList] = useState<MsgType[]>([])
  // 点击发送之后的函数
  const sendFu = () => {
    if (msg.trim() === '') return Toast.show({ content: '不能为空', maskClassName: 'and_toast_err' })
    setList([...list, { type: 'user', msg, timestamp: Date.now() }])

    //向 WebSocket服务器发送消息
    clientRef.current.emit('message', { msg, timestamp: Date.now() })

    setMsg('')
    setMsgState(true)
  }
  const msgInputKeyUp = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      if (msgState) return
      sendFu()
    }
  }


  // ------------WebSocket服务器
  const dispatch = useDispatch()
  const clientRef = useRef<any>(null)
  useEffect(() => {

    // 在本页面刷新，仓库的用户信息头像为空
    if (!userProfile.photo) dispatch(getUserProfile())


    // 进入页面创建实例
    const client = io(baseURL, {
      query: {
        token: getTokenInfo().token
      },
      transports: ['websocket']
    })
    // 连接成功之后
    client.on('connect', () => {
      setList([{ type: 'robot', msg: '亲爱的用户您好，小智同学为您服务。', timestamp: Date.now() }])
    })
    // 监听回来的消息添加到数据中
    client.on('message', data => {
      setList(oldData => [...oldData, { ...data, type: 'robot' }])
      setMsgState(false)
    })
    clientRef.current = client
    // 页面关闭的时候 关闭连接
    return () => {
      client.close()
    }

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dispatch])

  // 在列表变化的时候滚动到最底部
  useEffect(() => {
    window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' })
  }, [list])


  return (
    <div className={styles.root}>

      {/* 小智同学加载中 */}
      {
        msgState ?
          <div className='loadingBox'>
            <DotLoading color='primary' />
          </div>
          :
          null
      }


      {/* 顶部导航栏 */}
      <NavBar onBack={()=>history.push('/Layout/profile')} fixed={true}>小智同学</NavBar>

      {/* 聊天记录列表 - 开始 */}
      <div className='chat-list'>
        {list.map((item) => {
          return (
            item.type === 'robot' ?
              <div className='chat-item robot' key={item.timestamp}>
                <Icon type='iconbtn_xiaozhitongxue' />
                <div className='message'>{item.msg}</div>
              </div>
              :
              <div className='chat-item user' key={item.timestamp}>
                <img src={userProfile.photo} alt='' />
                <div className='message'>{item.msg}</div>
              </div>
          )
        })}
      </div>
      {/* 聊天记录列表 - 结束 */}

      {/* 底部消息输入框 */}
      <div className='footer'>
        <div className='input-footer'>
          <Icon type='iconbianji' />
          <Input onKeyUp={(e) => msgInputKeyUp(e)} value={msg} onChange={(e) => setMsg(e.target.value)} autoFocus className='no-border' placeholder='请描述您的问题' />
          <span className={classNames('send', msgState ? 'self_noneAc' : '')} onClick={sendFu}>发送</span>
        </div>
      </div>
    </div>
  )
}
